import * as THREE from 'three'
export class ClickHandler {
    static getInstance () {
        if (!this.instance) {
            this.instance = new ClickHandler()
        }
        return this.instance
    }
    
    init (camera) {
        this.camera = camera
        this.list = []
        this.map = new Map()

        // 光线投射
        this.raycaster = new THREE.Raycaster()
        const pointer = new THREE.Vector2()
        window.addEventListener('click', (e) => {
            // 点击建筑限触发这里
            e.stopPropagation()
            pointer.x = (e.clientX / window.innerWidth) * 2 - 1
            pointer.y = -(e.clientY / window.innerHeight) * 2 + 1

            this.raycaster.setFromCamera(pointer, this.camera)
            const resultList = this.raycaster.intersectObjects(this.list, false)
            console.log(resultList, 'resultList');

            // 默认只触发第一个点击到的物体
            if (resultList.length > 0) {
                const targetObj = resultList[0]
                // 执行这里的回调
                const fn = this.map.get(targetObj.object)
                // 回调绑定点击事件函数体，并回传当前触发的这个three.js物体
                fn && fn(targetObj.object)
            }
        })
    }

    addMesh(mesh, fn) {
        this.list.push(mesh)
        this.map.set(mesh, fn)
    }
}
